import { useState, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
import './SupermarketAlarmPanel.css';
import axios from 'axios';

const storeOptions = ['全部门店', '北京总店', '上海分店', '广州分店', '深圳分店'];
const categoryOptions = ['全部类别', '生鲜', '饮料', '零食', '日用品'];
// 定义数据类型
interface StoreData { 
  id: number;
  store: string;
  category: string;
  name: string;
  stock: number;
  alarm: string;
}
const initialMockData: StoreData[] = [
  {
    id: 1,
    store: "北京总店",
    category: "生鲜",
    name: "苹果",
    stock: 120,
    alarm: "正常",
  },
  {
    id: 2,
    store: "北京总店",
    category: "饮料",
    name: "可乐",
    stock: 10,
    alarm: "短缺",
  },
  {
    id: 3,
    store: "上海分店",
    category: "零食",
    name: "薯片",
    stock: 300,
    alarm: "积压",
  },
  {
    id: 4,
    store: "广州分店",
    category: "日用品",
    name: "牙膏",
    stock: 15,
    alarm: "短缺",
  },
  {
    id: 5,
    store: "深圳分店",
    category: "生鲜",
    name: "香蕉",
    stock: 5,
    alarm: "严重",
  },
  {
    id: 6,
    store: "深圳分店",
    category: "饮料",
    name: "雪碧",
    stock: 250,
    alarm: "积压",
  },
  {
    id: 7,
    store: "北京总店",
    category: "零食",
    name: "巧克力",
    stock: 20,
    alarm: "正常",
  },
  {
    id: 8,
    store: "上海分店",
    category: "日用品",
    name: "洗衣液",
    stock: 8,
    alarm: "严重",
  },
  {
    id: 9,
    store: "深圳分店",
    category: "生鲜",
    name: "橙子",
    stock: 60,
    alarm: "正常",
  },
  {
    id: 10,
    store: "北京总店",
    category: "饮料",
    name: "果汁",
    stock: 12,
    alarm: "短缺",
  },
];

// const mockData = [
//   { id: 1, store: '北京总店', category: '生鲜', name: '苹果', stock: 120, alarm: '正常' },
//   { id: 2, store: '北京总店', category: '饮料', name: '可乐', stock: 10, alarm: '短缺' },
//   { id: 3, store: '上海分店', category: '零食', name: '薯片', stock: 300, alarm: '积压' },
//   { id: 4, store: '广州分店', category: '日用品', name: '牙膏', stock: 15, alarm: '短缺' },
//   { id: 5, store: '深圳分店', category: '生鲜', name: '香蕉', stock: 5, alarm: '严重' },
//   { id: 6, store: '深圳分店', category: '饮料', name: '雪碧', stock: 250, alarm: '积压' },
//   { id: 7, store: '北京总店', category: '零食', name: '巧克力', stock: 20, alarm: '正常' },
//   { id: 8, store: '上海分店', category: '日用品', name: '洗衣液', stock: 8, alarm: '严重' },
//   { id: 9, store: '深圳分店', category: '生鲜', name: '橙子', stock: 60, alarm: '正常' },
//   { id: 10, store: '北京总店', category: '饮料', name: '果汁', stock: 12, alarm: '短缺' },
// ];

const alarmColor = {
  '严重': '#ff4e4e',
  '短缺': '#ffc300',
  '积压': '#1eaaff',
  '正常': '#6ed6ff',
};

const SupermarketAlarmPanel: React.FC = () => {
  const [store, setStore] = useState('全部门店');
  const [category, setCategory] = useState('全部类别');
  const [shortageThreshold, setShortageThreshold] = useState(15);
  const [overstockThreshold, setOverstockThreshold] = useState(200);
  const [page, setPage] = useState(1);
  const pageSize = 5;
  const [mockData, setMockData] = useState<StoreData[]>(initialMockData);

  function getData() {
    axios.get("http://localhost:3000/supermarket").then((res) => {
      setMockData(res.data.data.slice(0, 20));
      console.log(res.data.data);
    });
  }
  useEffect(() => {
    getData();
  }, []);

  // 数据筛选
  const filtered = mockData.filter(item =>
    (store === '全部门店' || item.store === store) &&
    (category === '全部类别' || item.category === category)
  ).map(item => {
    let alarm = '正常';
    if (item.stock <= shortageThreshold) alarm = item.stock <= shortageThreshold / 2 ? '严重' : '短缺';
    else if (item.stock >= overstockThreshold) alarm = '积压';
    return { ...item, alarm };
  });

  // 分页
  const total = filtered.length;
  const pageData = filtered.slice((page - 1) * pageSize, page * pageSize);
  const totalPages = Math.ceil(total / pageSize);

  // ECharts 配置
  const barOption = {
    title: { text: '库存告警条形图', left: 'center', textStyle: { color: '#6ed6ff', fontSize: 18 } },
    tooltip: {},
    xAxis: { type: 'category', data: filtered.map(i => i.name), axisLabel: { color: '#fff' } },
    yAxis: { type: 'value', axisLabel: { color: '#fff' } },
    series: [
      {
        name: '库存',
        type: 'bar',
        data: filtered.map(i => ({ value: i.stock, itemStyle: { color: alarmColor[i.alarm as keyof typeof alarmColor] } })),
        barWidth: 24,
      },
    ],
  };

  const scatterOption = {
    title: { text: '库存告警散点图', left: 'center', textStyle: { color: '#6ed6ff', fontSize: 18 } },
    tooltip: {},
    xAxis: { type: 'category', data: filtered.map(i => i.name), axisLabel: { color: '#fff' } },
    yAxis: { type: 'value', axisLabel: { color: '#fff' } },
    series: [
      {
        name: '库存',
        type: 'scatter',
        symbolSize: 24,
        data: filtered.map(i => ({ value: i.stock, itemStyle: { color: alarmColor[i.alarm as keyof typeof alarmColor] } })),
      },
    ],
  };

  return (
    <div className="alarm-panel">
      <div className="alarm-filters">
        <select value={store} onChange={e => setStore(e.target.value)}>
          {storeOptions.map(s => <option key={s}>{s}</option>)}
        </select>
        <select value={category} onChange={e => setCategory(e.target.value)}>
          {categoryOptions.map(c => <option key={c}>{c}</option>)}
        </select>
        <span>短缺阈值：</span>
        <input type="number" value={shortageThreshold} min={1} max={overstockThreshold-1} onChange={e => setShortageThreshold(Number(e.target.value))} />
        <span>积压阈值：</span>
        <input type="number" value={overstockThreshold} min={shortageThreshold+1} onChange={e => setOverstockThreshold(Number(e.target.value))} />
      </div>
      <div className="alarm-charts">
        <ReactECharts option={barOption} style={{ height: 300, width: '48%' }} />
        <ReactECharts option={scatterOption} style={{ height: 300, width: '48%' }} />
      </div>
      <div className="alarm-list">
        <table>
          <thead>
            <tr>
              <th>门店</th>
              <th>类别</th>
              <th>商品</th>
              <th>库存</th>
              <th>告警级别</th>
            </tr>
          </thead>
          <tbody>
            {pageData.map(item => (
              <tr key={item.id} className="alarm-row" onClick={() => alert(`跳转到${item.store}详情页（预留）`)} style={{ cursor: 'pointer' }}>
                <td>{item.store}</td>
                <td>{item.category}</td>
                <td>{item.name}</td>
                <td>{item.stock}</td>
                <td style={{ color: alarmColor[item.alarm as keyof typeof alarmColor], fontWeight: 'bold' }}>{item.alarm}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="alarm-pagination">
          <button disabled={page === 1} onClick={() => setPage(page - 1)}>上一页</button>
          <span>{page} / {totalPages}</span>
          <button disabled={page === totalPages} onClick={() => setPage(page + 1)}>下一页</button>
        </div>
      </div>
    </div>
  );
} 

export default SupermarketAlarmPanel;

